package com.gdsdxy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gdsdxy.dto.ResultVo;
import com.gdsdxy.dto.UserDTO;
import com.gdsdxy.entity.Follow;
import com.gdsdxy.entity.UserInfo;
import com.gdsdxy.mapper.FollowMapper;
import com.gdsdxy.service.IFollowService;
import com.gdsdxy.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    FollowMapper followMapper;

    @Override
    public ResultVo follow(Long followUserId, Boolean isFollow) {
        //1.获取登录用户
        UserDTO user = UserHolder.getUser();
        Long userId = user.getId();
        String key="follows"+userId;
        //判断是关注还是取关
        if (isFollow) {
            //2.关注，新增数据
            Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setFollowUserId(followUserId);
            follow.setCreateTime(LocalDateTime.now());
            boolean isSuccess = save(follow);
        } else {
            //取关，删除数据
            //sql: delete from tb_follow where user_id = ? and follow_user_id = ?
            Boolean isSuccess=remove(new QueryWrapper<Follow>()
                    .eq("user_id", userId)
                    .eq("follow_user_id", followUserId)
            );
        }
        return ResultVo.ok();
    }

    @Override
    public ResultVo isFollow(Long followUserId) {
        //1.获取用户
        UserDTO user = UserHolder.getUser();
        Long userId = user.getId();
        //查询是否关注
        //sql: select * from tb_follow where user_id = ? and follow_user_id
        Integer count = query().eq("user_id", userId).eq("follow_user_id", followUserId).count();
        return ResultVo.ok(count>0);
    }

    //根据用户id获取关注列表
    @Override
    public List<Follow> selectFollow(Long userId) {
        //1.获取用户
        UserDTO user = UserHolder.getUser();
        userId = user.getId();
        return followMapper.selectFollow(userId);
    }

    //根据用户id获取粉丝列表
    @Override
    public List<Follow> selectFans(Long followUserId) {
        UserDTO user = UserHolder.getUser();
        followUserId = user.getId();
        return followMapper.selectFans(followUserId);
    }

}
